<template>
  <div class="visit-detail">
    <!-- 基本信息 -->
    <el-card class="detail-section">
      <template #header>
        <div class="section-header">
          <span class="section-title">基本信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="挂号编号">
          {{ visitData.appointment_id }}
        </el-descriptions-item>
        <el-descriptions-item label="就诊记录ID">
          {{ visitData.visit_id }}
        </el-descriptions-item>
        <el-descriptions-item label="患者姓名">
          {{ visitData.patient_name }}
        </el-descriptions-item>
        <el-descriptions-item label="身份证号">
          {{ visitData.id_number }}
        </el-descriptions-item>
        <el-descriptions-item label="医保卡号">
          {{ visitData.insurance_card_number }}
        </el-descriptions-item>
        <el-descriptions-item label="手机号码">
          {{ visitData.phone_number || "无" }}
        </el-descriptions-item>
        <el-descriptions-item label="性别">
          <el-tag>{{ calculateGenderFromID(visitData.id_number) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="年龄">
          {{ calculateAgeFromID(visitData.id_number) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 挂号信息 -->
    <el-card class="detail-section">
      <template #header>
        <div class="section-header">
          <span class="section-title">挂号信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="就诊类型">
          <el-tag :type="getVisitTypeTagType(visitData.visit_type)">
            {{ getVisitTypeText(visitData.visit_type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="挂号状态">
          <el-tag :type="getStatusTagType(visitData.visit_status)">
            {{ getStatusText(visitData.visit_status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="挂号费用">
          <span class="fee-text">¥{{ visitData.registration_fee }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="挂号时间">
          {{ formatDateTime(visitData.registration_time) }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDateTime(visitData.create_time) }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ formatDateTime(visitData.update_time) }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 就诊安排 -->
    <el-card class="detail-section">
      <template #header>
        <div class="section-header">
          <span class="section-title">就诊安排</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="就诊科室">
          {{ visitData.department_name }}
        </el-descriptions-item>
        <el-descriptions-item label="接诊医生">
          {{ visitData.doctor_name || "未分配" }}
        </el-descriptions-item>
        <el-descriptions-item label="排班实例ID">
          {{ visitData.schedule_instance_id || "无" }}
        </el-descriptions-item>
        <el-descriptions-item label="就诊时间">
          {{
            visitData.visit_time
              ? formatDateTime(visitData.visit_time)
              : "未安排"
          }}
        </el-descriptions-item>
        <el-descriptions-item label="完成时间">
          {{
            clinicalData.diagnosis_time
              ? formatDateTime(clinicalData.diagnosis_time)
              : "未完成"
          }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 临床信息 -->
    <el-card class="detail-section">
      <template #header>
        <div class="section-header">
          <span class="section-title">临床信息</span>
          <el-tag
            :type="getDiagnosisStatusTagType(clinicalData.diagnosis_status)"
            size="small"
          >
            {{ getDiagnosisStatusText(clinicalData.diagnosis_status) }}
          </el-tag>
        </div>
      </template>
      <div class="clinical-info">
        <div class="info-item">
          <label class="info-label">主诉：</label>
          <div class="info-content">
            {{ clinicalData.chief_complaint || "无" }}
          </div>
        </div>
        <div class="info-item">
          <label class="info-label">现病史：</label>
          <div class="info-content">
            {{ clinicalData.present_illness || "无" }}
          </div>
        </div>
        <div class="info-item">
          <label class="info-label">既往史：</label>
          <div class="info-content">
            {{ clinicalData.past_history || "无" }}
          </div>
        </div>
        <div class="info-item">
          <label class="info-label">过敏史：</label>
          <div class="info-content">
            {{ clinicalData.allergy_history || "无" }}
          </div>
        </div>
        <div class="info-item">
          <label class="info-label">体格检查：</label>
          <div class="info-content">
            {{ clinicalData.physical_exam || "无" }}
          </div>
        </div>
      </div>
    </el-card>

    <!-- 诊断信息 -->
    <el-card class="detail-section">
      <template #header>
        <div class="section-header">
          <span class="section-title">诊断信息</span>
        </div>
      </template>
      <div class="clinical-info">
        <div class="info-item">
          <label class="info-label">初步诊断：</label>
          <div class="info-content">
            {{ clinicalData.preliminary_diagnosis || "无" }}
          </div>
        </div>
        <div class="info-item">
          <label class="info-label">最终诊断：</label>
          <div class="info-content diagnosis-result">
            {{ clinicalData.current_diagnosis || "无" }}
          </div>
        </div>
        <div class="info-item">
          <label class="info-label">疾病编码：</label>
          <div class="info-content">
            {{ clinicalData.disease_code || "无" }}
          </div>
        </div>
        <div class="info-item">
          <label class="info-label">治疗方案：</label>
          <div class="info-content">
            {{ clinicalData.treatment_plan || "无" }}
          </div>
        </div>
        <div class="info-item">
          <label class="info-label">辅助检查结果：</label>
          <div class="info-content">
            {{ clinicalData.lab_results || "无" }}
          </div>
        </div>
        <div class="info-item" v-if="clinicalData.diagnosis_time">
          <label class="info-label">诊断时间：</label>
          <div class="info-content">
            {{ formatDateTime(clinicalData.diagnosis_time) }}
          </div>
        </div>
      </div>
    </el-card>

    <!-- AI辅助诊断 -->
    <el-card class="detail-section" v-if="hasAIData">
      <template #header>
        <div class="section-header">
          <span class="section-title">AI辅助诊断</span>
          <el-tag type="info" size="small">AI分析</el-tag>
        </div>
      </template>
      <div class="clinical-info">
        <div class="info-item" v-if="clinicalData.ai_symptom_analysis">
          <label class="info-label">症状分析：</label>
          <div class="info-content ai-content">
            {{ clinicalData.ai_symptom_analysis }}
          </div>
        </div>
        <div class="info-item" v-if="clinicalData.ai_physical_exam_suggest">
          <label class="info-label">体格检查建议：</label>
          <div class="info-content ai-content">
            {{ clinicalData.ai_physical_exam_suggest }}
          </div>
        </div>
        <div class="info-item" v-if="clinicalData.ai_lab_suggest">
          <label class="info-label">检查项目推荐：</label>
          <div class="info-content ai-content">
            {{ clinicalData.ai_lab_suggest }}
          </div>
        </div>
        <div class="info-item" v-if="clinicalData.ai_diagnosis_suggest">
          <label class="info-label">诊断建议：</label>
          <div class="info-content ai-content">
            {{ clinicalData.ai_diagnosis_suggest }}
          </div>
        </div>
        <div class="info-item" v-if="clinicalData.ai_treatment_suggest">
          <label class="info-label">治疗建议：</label>
          <div class="info-content ai-content">
            {{ clinicalData.ai_treatment_suggest }}
          </div>
        </div>
      </div>
    </el-card>

    <!-- 操作记录 -->
    <el-card class="detail-section" v-if="operationLogs.length > 0">
      <template #header>
        <div class="section-header">
          <span class="section-title">操作记录</span>
        </div>
      </template>
      <el-timeline>
        <el-timeline-item
          v-for="log in operationLogs"
          :key="log.id"
          :timestamp="formatDateTime(log.operation_time)"
          :type="getLogType(log.operation_type)"
        >
          {{ log.operator }} {{ getOperationText(log.operation_type) }}
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
//引入后端API
import { getDiagnosisRecordDetailByVisitId } from "@/api/doctor.js";

const props = defineProps({
  visitData: {
    type: Object,
    required: true,
    default: () => ({}),
  },
  visitId: {
    type: [String, Number],
    default: null,
  },
});

// 状态映射
const statusMap = {
  registered: "已挂号",
  in_consultation: "就诊中",
  completed: "已完成",
  cancelled: "已取消",
};

const visitTypeMap = {
  outpatient: "门诊",
  emergency: "急诊",
  inpatient: "住院",
};

const diagnosisStatusMap = {
  in_progress: "进行中",
  completed: "已完成",
};

// 操作类型映射
const operationMap = {
  create: "创建挂号",
  update: "更新信息",
  start: "开始就诊",
  complete: "完成就诊",
  cancel: "取消挂号",
};

// 临床数据 - 根据诊断记录表结构调整
const clinicalData = ref({
  // 临床信息
  chief_complaint: "",
  present_illness: "",
  past_history: "",
  allergy_history: "",
  physical_exam: "",

  // 诊断信息
  preliminary_diagnosis: "",
  current_diagnosis: "",
  disease_code: "",

  // 治疗信息
  treatment_plan: "",
  lab_results: "",

  // AI辅助字段
  ai_symptom_analysis: "",
  ai_physical_exam_suggest: "",
  ai_lab_suggest: "",
  ai_diagnosis_suggest: "",
  ai_treatment_suggest: "",
  ai_quick_analysis: null,

  // 状态信息
  diagnosis_status: "in_progress",
  diagnosis_time: null,
});

// 模拟操作日志数据
const operationLogs = ref([]);

// 计算属性
const hasAIData = computed(() => {
  return (
    clinicalData.value.ai_symptom_analysis ||
    clinicalData.value.ai_physical_exam_suggest ||
    clinicalData.value.ai_lab_suggest ||
    clinicalData.value.ai_diagnosis_suggest ||
    clinicalData.value.ai_treatment_suggest
  );
});

const getStatusText = (status) => {
  return statusMap[status] || status;
};

const getVisitTypeText = (type) => {
  return visitTypeMap[type] || type;
};

const getDiagnosisStatusText = (status) => {
  return diagnosisStatusMap[status] || status;
};

const getOperationText = (type) => {
  return operationMap[type] || type;
};

const getGenderText = (gender) => {
  const genderMap = {
    male: "男",
    female: "女",
    unknown: "未知",
  };
  return genderMap[gender] || gender;
};

const getStatusTagType = (status) => {
  const types = {
    registered: "primary",
    in_consultation: "warning",
    completed: "success",
    cancelled: "danger",
  };
  return types[status] || "";
};

const getVisitTypeTagType = (type) => {
  const types = {
    outpatient: "info",
    emergency: "danger",
    inpatient: "warning",
  };
  return types[type] || "";
};

const getDiagnosisStatusTagType = (status) => {
  const types = {
    in_progress: "warning",
    completed: "success",
  };
  return types[status] || "";
};

const getLogType = (operationType) => {
  const types = {
    create: "primary",
    update: "info",
    start: "warning",
    complete: "success",
    cancel: "danger",
  };
  return types[operationType] || "";
};

// 工具函数
const formatDateTime = (dateTime) => {
  if (!dateTime) return "";
  return new Date(dateTime).toLocaleString("zh-CN");
};

// 从身份证号计算性别
const calculateGenderFromID = (idNumber) => {
  if (!idNumber || idNumber.length !== 18) {
    return "未知";
  }
  // 获取第17位数字（性别位）
  const genderDigit = parseInt(idNumber.charAt(16));
  // 奇数为男性，偶数为女性
  return genderDigit % 2 === 1 ? "男" : "女";
};

// 从身份证号计算年龄
const calculateAgeFromID = (idNumber) => {
  if (!idNumber || idNumber.length !== 18) {
    return "";
  }
  
  try {
    // 提取出生年月日
    const birthYear = parseInt(idNumber.substring(6, 10));
    const birthMonth = parseInt(idNumber.substring(10, 12)) - 1; // 月份从0开始
    const birthDay = parseInt(idNumber.substring(12, 14));
    
    const birthDate = new Date(birthYear, birthMonth, birthDay);
    const today = new Date();
    
    let age = today.getFullYear() - birthDate.getFullYear();
    const monthDiff = today.getMonth() - birthDate.getMonth();
    
    // 如果当前月份小于出生月份，或者月份相同但日期小于出生日期，则年龄减1
    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
      age--;
    }
    
    return `${age}岁`;
  } catch (error) {
    console.error("计算年龄出错:", error);
    return "";
  }
};

// 加载临床诊断信息 - 根据visit_id关联查询诊断记录表
const loadClinicalData = async () => {
  try {
    // TODO: 这里需要调用根据visit_id查询诊断记录信息的API
    // 接口位置：需要根据当前就诊记录ID关联查询 h_diagnosis_record_tb 表
    const response = await getDiagnosisRecordDetailByVisitId({
      visit_id: props.visitId,
    });
    console.log("获取的诊断记录信息:", response);
    if (response && response.code === 200) {
      clinicalData.value = response.data;
    } else {
      console.error("获取诊断记录信息失败");
      // 如果查询不到诊断记录，可以保持空数据或显示默认值
    }
  } catch (error) {
    console.error("加载诊断记录信息失败:", error);
  }
};

// 加载操作日志
const loadOperationLogs = async () => {
  try {
    // 模拟API调用
    await new Promise((resolve) => setTimeout(resolve, 300));

    // 操作日志数据
    const mockLogs = [
      {
        id: 1,
        operation_type: "create",
        operator: "系统",
        operation_time: props.visitData.create_time,
        description: `创建挂号记录，挂号编号：${props.visitData.appointment_id}`,
      },
    ];

    // 根据状态添加相应的操作记录
    if (props.visitData.visit_time) {
      mockLogs.push({
        id: 2,
        operation_type: "start",
        operator: props.visitData.doctor_name || "医生",
        operation_time: props.visitData.visit_time,
        description: "开始就诊",
      });
    }

    if (clinicalData.value.diagnosis_time) {
      mockLogs.push({
        id: 3,
        operation_type: "complete",
        operator: props.visitData.doctor_name || "医生",
        operation_time: clinicalData.value.diagnosis_time,
        description: "完成诊断",
      });
    }

    if (props.visitData.visit_status === "cancelled") {
      mockLogs.push({
        id: 4,
        operation_type: "cancel",
        operator: "管理员",
        operation_time: props.visitData.update_time,
        description: "取消挂号",
      });
    }

    // 按时间排序
    operationLogs.value = mockLogs.sort(
      (a, b) => new Date(a.operation_time) - new Date(b.operation_time)
    );
  } catch (error) {
    console.error("加载操作日志失败:", error);
  }
};

// 监听visitId变化，重新加载数据
watch(
  () => props.visitId,
  (newVisitId) => {
    if (newVisitId) {
      loadClinicalData();
      loadOperationLogs();
    }
  }
);

onMounted(() => {
  if (props.visitId) {
    loadClinicalData();
    loadOperationLogs();
  }
});
</script>

<style lang="scss" scoped>
.visit-detail {
  padding: 0;
}

.detail-section {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.clinical-info {
  .info-item {
    display: flex;
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .info-label {
    font-weight: 500;
    color: #606266;
    min-width: 120px;
    margin-right: 12px;
    flex-shrink: 0;
  }

  .info-content {
    flex: 1;
    color: #303133;
    line-height: 1.6;
    background: #f8f9fa;
    padding: 12px;
    border-radius: 4px;
    border-left: 4px solid #409eff;
    white-space: pre-wrap;
  }

  .diagnosis-result {
    border-left-color: #67c23a;
    background: #f0f9ff;
  }

  .ai-content {
    border-left-color: #909399;
    background: #f4f4f5;
    font-style: italic;
  }
}

.fee-text {
  font-weight: 600;
  color: #e6a23c;
  font-size: 16px;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  background-color: #f8f9fa;
}

:deep(.el-descriptions__content) {
  font-weight: 400;
}

:deep(.el-timeline) {
  padding-left: 10px;
}

:deep(.el-timeline-item__timestamp) {
  color: #909399;
  font-size: 12px;
}
</style>